package com.wyu.test.web;

import com.wyu.test.entity.CUserEntity;
import com.wyu.test.repository.CUserEntityRepository;
import com.wyu.test.util.JsonCode;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;

@RestController
@RequestMapping("/api")
public class UserMessageWebController {

    //用户信息
    //查看/添加/删除/修改

    @Autowired
    CUserEntityRepository cUserEntityRepository;


    //查询用户信息
    @GetMapping(value = "/userMessage")
    public String userMessage(HttpServletRequest request,
                              @RequestParam(value = "username",required = true) String username
    ){

        CUserEntity cUserEntity = cUserEntityRepository.findFirstByUsername(username);
        if(cUserEntity == null){
            return new JsonCode<>().ResponseFail(99,"log_out");
        }

        return new JsonCode<>().ResponseSuccess(cUserEntity);

    }

    //添加用户信息
    @PostMapping(value = "/userMessage")
    public String addUserMessage(HttpServletRequest request,
                              @RequestParam(value = "username",required = true) String username,
                              @RequestParam(value = "phone",required = true) String phone
    ){

        CUserEntity cUserEntity = new CUserEntity();
        cUserEntity.setUsername(username);
        cUserEntity.setPhone(phone);
        cUserEntityRepository.saveAndFlush(cUserEntity);

        return new JsonCode<>().ResponseSuccess();

    }

    //修改用户信息
    @PutMapping(value = "/userMessage")
    public String changeUserMessage(HttpServletRequest request,
                                 @RequestParam(value = "username",required = true) String username,
                                 @RequestParam(value = "phone",required = true) String phone
    ){

        CUserEntity cUserEntity = cUserEntityRepository.findFirstByUsername(username);
        if(cUserEntity == null){
            return new JsonCode<>().ResponseFail(99,"log_out");
        }

        cUserEntity.setPhone(phone);
        cUserEntityRepository.save(cUserEntity);

        return new JsonCode<>().ResponseSuccess();

    }

    //删除用户信息
    @DeleteMapping(value = "/userMessage")
    public String deleteUserMessage(HttpServletRequest request,
                                 @RequestParam(value = "username",required = true) String username
    ){

        CUserEntity cUserEntity = cUserEntityRepository.findFirstByUsername(username);
        if(cUserEntity == null){
            return new JsonCode<>().ResponseFail(99,"log_out");
        }

        cUserEntityRepository.delete(cUserEntity);

        return new JsonCode<>().ResponseSuccess();

    }

}
